package com.aivin.txSms;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

/**
 * Created by Administrator on 2016/10/21.
 */
public class SmsSender {
    Random random = new Random();
    int sdkappid;
    String appkey;
    // 请根据我们的说明文档适时调整 url
    final String url = "https://yun.tim.qq.com/v3/tlssmssvr/sendsms";

    public SmsSender(int sdkappid, String appkey) {
        this.sdkappid = sdkappid;
        this.appkey = appkey;
    }

    public String  sendMsg(String nationCode, String phoneNumber, String content) {
        String resultStr="init";
        long rnd = random.nextInt(999999)%(999999-100000+1)+100000;
        String wholeUrl = String.format("%s?sdkappid=%d&random=%d", url, sdkappid, rnd);
        try {
            URL object = new URL(wholeUrl);
            HttpURLConnection con = (HttpURLConnection) object.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestMethod("POST");
            JSONObject data = new JSONObject();
            JSONObject tel = new JSONObject();
            tel.put("nationcode", nationCode);
            String phone = phoneNumber;
            tel.put("phone", phone);
            data.put("type", "0"); ////0:普通短信;1:营销短信（强调：要按需填值，不然会影响到业务的正常使用）
            data.put("msg", content); //"msg"字段需要匹配审核通过的模板内容
            String sig = SMSUtils.stringMD5(appkey.concat(phone));
            data.put("sig", sig);
            data.put("tel", tel);
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
            wr.write(data.toString());
            wr.flush();


            System.out.println("请求下发短信验证码的请求包体内容是:\n"+data.toString());
            // 显示 POST 请求返回的内容
            StringBuilder sb = new StringBuilder();
            int HttpResult = con.getResponseCode();

            if (HttpResult == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
               // System.out.println("请求返回结果>>\n" + sb.toString());
                resultStr = sb.toString() ;
            } else {
               // System.out.println("请求异常>>>"+con.getResponseMessage());
                resultStr = "服务器异常_"+ con.getResponseMessage() ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(">>>>>>>>>>>>>>>>收到一次验证码发送请求\n"+resultStr+"\n\n\n\n\n\n" );


        return  resultStr ;
    }


}
